﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Platform.Storage.Redis
{
	public sealed class RedisListCommands : RedisCommandsBase
	{
		internal RedisListCommands( string listName, RedisMessageChannel channel )
			: base( channel )
		{
			this.ListName = listName;
		}

		public string ListName
		{ get; private set; }

		public IEnumerable<string> Range( int start, int stop )
		{
			return this.Channel.ExecuteOrQuery( "LRANGE", this.ListName, Convert.ToString( start ), Convert.ToString( stop ) );
		}

		public string ElementAt( int index )
		{
			return this.Channel.ExecuteSingle( "LINDEX", this.ListName, Convert.ToString( index ) );
		}

		public int Count
		{
			get
			{
				return this.Channel.ExecuteInt32( "LLEN", this.ListName );
			}
		}

		public int Add( string value )
		{
			return this.Channel.ExecuteInt32( "RPUSH", this.ListName, value );
		}

		public int Add( params string[] values )
		{
			if ( values != null && values.Length > 0 )
				return this.Channel.ExecuteInt32( "RPUSH", new List<string>() { this.ListName }.Union( values ).ToArray() );
			else
				return this.Count;
		}

		public string RemoveFirst()
		{
			return this.Channel.ExecuteSingle( "LPOP", this.ListName );
		}

		public string RemoveLast()
		{
			return this.Channel.ExecuteSingle( "RPOP", this.ListName );
		}

		public void Zip( int start )
		{
			this.Zip( start, -1 );
		}

		public void Zip( int start, int stop )
		{
			this.Channel.ExecuteSingle( "LTRIM", this.ListName, start.ToString(), stop.ToString() );
		}

		public IEnumerable<string> GetAll()
		{
			return this.Range( 0, -1 );
		}
	}
}
